package com.orhon.smartcampus.modules.base.fetcher;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.DictionaryDao;
import com.orhon.smartcampus.modules.base.dao.SubjectsDao;
import com.orhon.smartcampus.modules.base.entity.Grades;
import com.orhon.smartcampus.modules.base.entity.Periods;
import com.orhon.smartcampus.modules.base.entity.Subjects;
import com.orhon.smartcampus.modules.base.gqlModel.GQLGrades;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPeriod;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSubject;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.GradeMapper;
import com.orhon.smartcampus.modules.base.mm.PeriodMapper;
import com.orhon.smartcampus.modules.base.mm.SubjectMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SubjectsFetcher implements DataFetcher {

	@Autowired
	DictionaryDao dictionaryDao;


	@Autowired
	SubjectsDao subjectsDao;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {
		List<GQLSubject> GQLSubject = new ArrayList<>();
		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);

		String hql = "from Subjects where deleted_at = null ";
		List<Subjects> list = subjectsDao.find(hql,null,page.getPage(),page.getLimit());
		for (Subjects item : list) {
			List<GQLPeriod> gqlPeriod = null;
			if (env.getSelectionSet().contains("data/period")){
				List<Periods> periods = item.getPeriod();
				gqlPeriod = PeriodMapper.MAPPER.toPeriodsList(periods);
			}
			List<GQLGrades> gqlGrades = null;
			if (env.getSelectionSet().contains("data/grade")){
				List<Grades> grade = item.getGrade();
				gqlGrades = GradeMapper.MAPPER.toGradeList(grade);
			}
			GQLSubject subject = SubjectMapper.MAPPER.toSubject(item);
			subject.setPeriod(gqlPeriod);
			subject.setGrade(gqlGrades);
			GQLSubject.add(subject);
		}

		Long total = 0L;
		if (env.getSelectionSet().contains("total")){
			total = subjectsDao.getTotalCount(hql);
		}
		return Result.ok().put("data" , GQLSubject).put("total" , total);
	}


}
